package com.example.qa.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.qa.commonutils.R;
import com.example.qa.entity.ZhAnswer;
import com.example.qa.entity.ZhComment;
import com.example.qa.entity.vo.AnswerInfo;
import com.example.qa.service.ZhAnswerService;
import com.example.qa.service.ZhCommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-03-02
 */
@CrossOrigin
@RestController
@RequestMapping("/qa/answer")
public class ZhAnswerController {
@Autowired
private ZhAnswerService answerService;
@Autowired
private ZhCommentService commentService;
@GetMapping("/detail/{qustionId}")
    public R getAnswerByQuestionId(@PathVariable String qustionId){
    QueryWrapper<ZhAnswer>wrapper=new QueryWrapper<>();
    wrapper.eq("question_id",qustionId);
    List<ZhAnswer> answerList = answerService.list(wrapper);
    List<AnswerInfo>answerInfoList=new ArrayList<>();
    for (ZhAnswer answer:answerList) {
        AnswerInfo answerInfo=new AnswerInfo();
        BeanUtils.copyProperties(answer,answerInfo);
        answerInfoList.add(answerInfo);
        QueryWrapper<ZhComment>commentWrapper=new QueryWrapper<>();
        commentWrapper.eq("answer_id",answer.getId());
        int count = commentService.count(commentWrapper);
        answerInfo.setCommentsSize(count);
    }

    return R.ok().data("list",answerInfoList);
}
@PostMapping("/add")
    public R addAnswer(@RequestBody ZhAnswer answer)
{
    boolean save = answerService.save(answer);
    AnswerInfo answerInfo = new AnswerInfo();
    BeanUtils.copyProperties(answer,answerInfo);
    answerInfo.setShowComments(false);
    return R.ok().data("answer",answerInfo);
}
}

